当前位置:  开发笔记 > 编程语言 > 正文

AssertionError:`HyperlinkedIdentityField`需要序列化程序上下文中的请求

如何解决《AssertionError:`HyperlinkedIdentityField`需要序列化程序上下文中的请求》经验,为你挑选了3个好方法。

我想建立一种many-to-many关系,一个人可以在许多俱乐部,一个俱乐部可以有很多人.我加入了models.py,并serializers.py为下面的逻辑,但是当我试图序列化在命令提示符下,我碰到下面的错误-我是什么错在这里做什么?我连一个都没有HyperlinkedIdentityField

Traceback (most recent call last):
File "", line 1, in 
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 503, in data
ret = super(Serializer, self).data
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 472, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\user\corr\lib\site-packages\rest_framework\relations.py", line 320, in to_representation"the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.

models.py

class Club(models.Model):
    club_name = models.CharField(default='',blank=False,max_length=100)

class Person(models.Model):
    person_name = models.CharField(default='',blank=False,max_length=200)
    clubs = models.ManyToManyField(Club)

serializers.py

class ClubSerializer(serializers.ModelSerializer):
    class Meta:
        model = Club
        fields = ('url','id','club_name','person')

class PersonSerializer(serializers.ModelSerializer):
    clubs = ClubSerializer()
    class Meta:
        model = Person
        fields = ('url','id','person_name','clubs')

views.py

class ClubDetail(generics.ListCreateAPIView):
serializer_class = ClubSerializer

def get_queryset(self):
     club = Clubs.objects.get(pk=self.kwargs.get('pk',None))
     persons = Person.objects.filter(club=club)
     return persons

class ClubList(generics.ListCreateAPIView):
    queryset = Club.objects.all()
    serializer_class = ClubSerializer


class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = PersonSerializer


def get_object(self):
    person_id = self.kwargs.get('pk',None)
    return Person.objects.get(pk=person_id) 

检查创建的序列化器给了我这个 -

PersonSerializer():
url = HyperlinkedIdentityField(view_name='person-detail')
id = IntegerField(label='ID', read_only=True)
person_name = CharField(max_length=200, required=False)
clubs = ClubSerializer():
    url = HyperlinkedIdentityField(view_name='club-detail')
    id = IntegerField(label='ID', read_only=True)
    club_name = CharField(max_length=100, required=False)

但是serializer.data给了我错误

******************编辑*********************我意识到错误可能是因为url模式,所以我添加了以下网址模式,但我仍然得到错误 -

urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^clubs/$',
    views.ClubList.as_view(),
    name='club-list'),
 url(r'^clubs/(?P[0-9]+)/persons/$',
    views.ClubDetail.as_view(),
    name='club-detail'),
url(r'^person/(?P[0-9]+)/$',
    views.PersonDetail.as_view(),
    name='person-detail'),
])

Ashley 'CptL.. 32

你得到这个错误的HyperlinkedIdentityField期望接收requestcontext串行化的,因此它可以建立绝对的URL.在命令行上初始化序列化程序时,您无权访问请求,因此会收到错误.

如果需要在命令行上检查序列化程序,则需要执行以下操作:

from rest_framework.request import Request
from rest_framework.test import APIRequestFactory

from .models import Person
from .serializers import PersonSerializer

factory = APIRequestFactory()
request = factory.get('/')


serializer_context = {
    'request': Request(request),
}

p = Person.objects.first()
s = PersonSerializer(instance=p, context=serializer_context)

print s.data

你的网址字段看起来像http://testserver/person/1/.



1> Ashley 'CptL..:

你得到这个错误的HyperlinkedIdentityField期望接收requestcontext串行化的,因此它可以建立绝对的URL.在命令行上初始化序列化程序时,您无权访问请求,因此会收到错误.

如果需要在命令行上检查序列化程序,则需要执行以下操作:

from rest_framework.request import Request
from rest_framework.test import APIRequestFactory

from .models import Person
from .serializers import PersonSerializer

factory = APIRequestFactory()
request = factory.get('/')


serializer_context = {
    'request': Request(request),
}

p = Person.objects.first()
s = PersonSerializer(instance=p, context=serializer_context)

print s.data

你的网址字段看起来像http://testserver/person/1/.



2> Slipstream..:

我有两个解决方案......

urls.py

1) 如果您使用的是router.register,则可以添加base_name:

router.register(r'users', views.UserViewSet, base_name='users')
urlpatterns = [    
    url(r'', include(router.urls)),
]

2) 如果您有这样的事情:

urlpatterns = [    
    url(r'^user/$', views.UserRequestViewSet.as_view()),
]

您必须将上下文传递给序列化程序:

views.py

class UserRequestViewSet(APIView):            
    def get(self, request, pk=None, format=None):
        user = ...    
        serializer_context = {
            'request': request,
        }
        serializer = api_serializers.UserSerializer(user, context=serializer_context)    
        return Response(serializer.data)

像这样你可以继续使用你的序列化器上的url: serializers.py

...
url = serializers.HyperlinkedIdentityField(view_name="user")
...



3> Diansheng..:

我遇到了同样的问题.我的方法是从serializer.py中的Meta.fields中删除"url".

推荐阅读
手机用户2502852037
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有